package com.whfc.fse.xxl.job;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.whfc.XxlJobConfig;
import com.whfc.base.dto.AppSyncDTO;
import com.whfc.base.service.SyncConfigService;
import com.whfc.common.constant.QueueConst;
import com.whfc.common.enums.DevicePlatform;
import com.whfc.common.enums.SyncPlatform;
import com.whfc.common.util.DateUtil;
import com.whfc.common.util.MathUtil;
import com.whfc.fse.dto.*;
import com.whfc.fse.entity.FseLift;
import com.whfc.fse.enums.FseWarnRuleType;
import com.whfc.fse.manager.FseCraneSZJDataMgr;
import com.whfc.fse.manager.FseLiftSZJDataMgr;
import com.whfc.fse.service.FseCraneService;
import com.whfc.fse.service.FseLiftService;
import com.xxl.job.core.handler.annotation.XxlJob;
import groovyjarjarpicocli.CommandLine;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Component
@ConditionalOnBean(XxlJobConfig.class)
public class FseLiftSZJDataJob {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @DubboReference(interfaceClass = SyncConfigService.class, version = "1.0.0")
    private SyncConfigService syncConfigService;

    @Autowired
    private FseLiftService fseLiftService;

    @Autowired
    private FseLiftSZJDataMgr fseLiftSZJDataMgr;

    @Resource(name = "baseRabbitTemplate")
    private AmqpTemplate amqpTemplate;

    /**
     * 宇泛数智建平台-实时数据
     */
    @XxlJob("szj-liftData")
    public void getCraneData() {
        logger.info("开始执行从宇泛数智建平台拉取升降机设备数据");
        List<AppSyncDTO> appSyncDTOS = syncConfigService.selectByPlatform(SyncPlatform.SZJ.getValue());
        if (CollectionUtils.isEmpty(appSyncDTOS)) {
            logger.info("未获取到配置");
            return;
        }
        Date endDate = new Date();

        for (AppSyncDTO appSyncDTO : appSyncDTOS) {
            List<FseLift> craneDTOS = fseLiftService.list(appSyncDTO.getProjectId(), DevicePlatform.yufanszj.name());
            if (CollectionUtils.isEmpty(craneDTOS)) {
                logger.info("该项目无宇泛数智建平台升降机设备,项目id={}", appSyncDTO.getProjectId());
                continue;
            }
            String token = syncConfigService.getSZJSyncToken(appSyncDTO.getProjectId(), appSyncDTO.getPlatform(), appSyncDTO.getAppSecret());
            for (FseLift fseLift : craneDTOS) {
                // 如果左边已绑定
                if (1==fseLift.getLeftBindFlag()) {
                    // 实时数据
                    getRealData(appSyncDTO.getProjectId(), fseLift.getLeftSn(), endDate, token);
                    // 工作循环
                    getWorkData(appSyncDTO.getProjectId(), fseLift.getLeftSn(), endDate, token);
                }
                // 如果右边已绑定
                if (1==fseLift.getRightBindFlag()) {
                    // 实时数据
                    getRealData(appSyncDTO.getProjectId(), fseLift.getRightSn(), endDate, token);
                    // 工作循环
                    getWorkData(appSyncDTO.getProjectId(), fseLift.getRightSn(), endDate, token);
                }
            }
        }

    }

    // 实时数据
    public void getRealData(Integer deptId, String deviceKey, Date endDate, String token) {
        Date startDate = DateUtil.addMinutes(endDate, -2);
        String startTime = DateUtil.formatDateTime(startDate);
        String endTime = DateUtil.formatDateTime(endDate);
        // 实时数据
        JSONObject realData = fseLiftSZJDataMgr.getLiftRealData(deviceKey, 1, 1, startTime, endTime, token);
        if (realData == null) {
            logger.info("未获取到升降机设备数据,项目id={},sn={},startTime={},endTime={}", deptId, deviceKey, startTime, endTime);
            return;
        }
        FseLiftDataDTO fseLiftDataDTO = new FseLiftDataDTO();
        // 设备唯一标识
        fseLiftDataDTO.setSn(deviceKey);
        // 探越
        fseLiftDataDTO.setPlatform(DevicePlatform.yufanszj.name());
        setLiftData(realData, fseLiftDataDTO);
        amqpTemplate.convertAndSend(QueueConst.FSE_LIFT_REAL_DATA, JSONObject.toJSONString(fseLiftDataDTO));
    }


    public void getWorkData(Integer deptId, String deviceKey, Date endDate, String token) {
        Date startDate = DateUtil.addMinutes(endDate, -2);
        String startTime = DateUtil.formatDateTime(startDate);
        String endTime = DateUtil.formatDateTime(endDate);

        JSONArray workData = fseLiftSZJDataMgr.getLiftWorkData(deviceKey, 1, 20, startTime, endTime, token);
        if (CollectionUtils.isEmpty(workData)) {
            logger.info("未获取到升降机设备工作数据,项目id={},sn={},startTime={},endTime={}", deptId, deviceKey, startTime, endTime);
            return;
        }
        for (Object craneWorkDatum : workData) {
            JSONObject json = JSONObject.parseObject(craneWorkDatum.toString());
            // 转换成平台数据
            FseLiftRecordDTO fseLiftDataDTO = new FseLiftRecordDTO();
            // 设备唯一标识
            fseLiftDataDTO.setSn(deviceKey);
            fseLiftDataDTO.setPlatform(DevicePlatform.yufanszj.name());
            // 重量
            Double weight = json.getDouble("weight");
            fseLiftDataDTO.setWeight(weight);
            // 开始高度
            Double start_height = json.getDouble("startHeight");
            fseLiftDataDTO.setStartHeight(start_height*0.1);
            // 结束高度
            Double end_height = json.getDouble("stopHeight");
            fseLiftDataDTO.setEndHeight(end_height*0.1);
            // 人数
            Integer number = json.getInteger("peopleCount");
            fseLiftDataDTO.setPersonNo(number);
            // 速度
            Double speed = json.getDouble("averageSpeed");
            fseLiftDataDTO.setAvgSpeed(speed);
            // 倾角x轴
            Double tilt_x = json.getDouble("maxXLean");

            fseLiftDataDTO.setDipAngleX(tilt_x);
            // 倾角y轴
            Double tilt_y = json.getDouble("maxYLean");

            fseLiftDataDTO.setDipAngleY(tilt_y);
            // 开始时间
            String start_time = json.getString("startTime");
            fseLiftDataDTO.setStartTime(getDateTime(start_time));
            // 结束时间
            String end_time = json.getString("endTime");
            fseLiftDataDTO.setEndTime(getDateTime(end_time));
            amqpTemplate.convertAndSend(QueueConst.FSE_LIFT_RECORD_DATA, JSONObject.toJSONString(fseLiftDataDTO));
        }
    }


    // 获取日期
    private Date getDateTime(String dateTime) {
        // "2022-03-01T15:41:00.000+0800"
        String replace = dateTime.substring(0, 19).replace("T", " ");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date parse = null;
        try {
            parse = sdf.parse(replace);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return parse;
    }

    // 设置实时数据
    private void setLiftData(JSONObject json, FseLiftDataDTO fseLiftDataDTO) {
        // 高度
        Double height = json.getDouble("height");
        fseLiftDataDTO.setHeight(MathUtil.round(height * 0.1, 1));
        // 重量
        Double weight = json.getDouble("load");
        fseLiftDataDTO.setWeight(MathUtil.round(weight * 0.001, 3));
        // 速度
        Double speed = json.getDouble("speed");
        fseLiftDataDTO.setSpeed(speed);
        // 风速
        Double wind_speed = json.getDouble("windSpeed");
        fseLiftDataDTO.setWindSpeed(wind_speed);
        // 人数
        Integer number = json.getInteger("peopleNum");
        fseLiftDataDTO.setPersonNo(number);
        // 倾斜
        Double tilt_x = json.getDouble("leanGradient1");
        fseLiftDataDTO.setDipAngle(tilt_x);
        // 前门
        Integer front_door_status = json.getInteger("frontDoor");
        front_door_status = front_door_status == 1 ? 2 : 0;
        fseLiftDataDTO.setFrontDoorState(front_door_status);
        // 后门
        Integer back_door_status = json.getInteger("backDoor");
        back_door_status = back_door_status == 1 ? 2 : 0;
        fseLiftDataDTO.setBackDoorState(back_door_status);
        String businessTime = json.getString("businessTime");
        fseLiftDataDTO.setTime(getDateTime(businessTime));
    }
}

